package app.itgungnir.compose.wan.business.my_website

import androidx.lifecycle.ViewModel
import androidx.room.withTransaction
import app.itgungnir.compose.wan.utils.WanDatabase
import app.itgungnir.compose.wan.utils.launch
import app.itgungnir.compose.wan.utils.wanAndroidService
import app.itgungnir.compose.wan.utils.wanResponse
import com.google.gson.JsonElement
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow

class MyWebsiteViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val dialogLoadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    val dialogErrorState = MutableSharedFlow<Throwable?>()
    val dismissDialogState = MutableStateFlow(false)
    var loadingJob: Job? = null
    var dialogLoadingJob: Job? = null

    val myWebsiteFlow = WanDatabase.dao.queryMyWebsites()

    init {
        launch {
            wanAndroidService.getMyWebsites().wanResponse<List<MyWebsite>>()?.takeIf { it.isNotEmpty() }?.let { list ->
                WanDatabase.instance.withTransaction {
                    WanDatabase.dao.deleteAllMyWebsites()
                    WanDatabase.dao.insertAllMyWebsites(list)
                }
            }
        }
    }

    fun addWebsite(name: String, link: String) = launch(dialogLoadingState, dialogErrorState) {
        if (name.isEmpty()) {
            throw IllegalArgumentException("标题不能为空")
        }
        if (link.isEmpty()) {
            throw IllegalArgumentException("链接不能为空")
        }
        dismissDialogState.emit(false)
        val response = wanAndroidService.addWebsite(name, link).wanResponse<MyWebsite>()
        response?.takeIf { it.id > 0 }?.let {
            WanDatabase.dao.insertMyWebsite(it)
        }
        dismissDialogState.emit(true)
    }.also { dialogLoadingJob = it }

    fun updateWebsite(website: MyWebsite) = launch(dialogLoadingState, dialogErrorState) {
        if (website.name.isNullOrEmpty()) {
            throw IllegalArgumentException("标题不能为空")
        }
        if (website.link.isNullOrEmpty()) {
            throw IllegalArgumentException("链接不能为空")
        }
        dismissDialogState.emit(false)
        wanAndroidService.updateWebsite(website.id, website.name, website.link).wanResponse<JsonElement>()
        WanDatabase.dao.updateMyWebsite(website)
        dismissDialogState.emit(true)
    }.also { dialogLoadingJob = it }

    fun deleteWebsite(website: MyWebsite) = launch(loadingState, errorState) {
        val websiteId = website.id
        wanAndroidService.deleteWebsite(websiteId).wanResponse<JsonElement>()
        WanDatabase.dao.deleteMyWebsite(websiteId)
    }.also { loadingJob = it }
}
